package com.example.security.springboot.service;

import com.example.security.springboot.dao.UserDao;
import com.example.security.springboot.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhuyaotong
 * @date 2021/6/1
 */
@Service
public class SpringDataUserDetailsService implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    /**
     * 根据账号查询用户信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserDto user = userDao.getUserByUsername(username);

        if (user == null) {
            return null;
        }

        // 根据用户的 ID 查询用户的权限
        List<String> permissions = userDao.findPermissionByUserId(user.getId());

        String[] permissionArray = new String[permissions.size()];
        permissions.toArray(permissionArray);

        UserDetails userDetails = User.withUsername(user.getUsername())
                .password(user.getPassword())
                .authorities(permissionArray).build();

        return userDetails;

    }

}
